package com.hkbigdata.springbootdi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hkbigdata.springbootdi.bean.*;
import com.hkbigdata.springbootdi.mapper.ESDao;
import com.hkbigdata.springbootdi.mapper.OrderStatusMapper;
import com.hkbigdata.springbootdi.service.DIService;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author liuanbo
 * @creat 2024-11-27-15:40
 * @see 2194550857@qq.com
 */
@Service
public class DiServiceImpl implements DIService {

    @Autowired
    OrderStatusMapper orderStatusMapper;

    @Override
    public ResponData getOrderStatus(String dt) {
        List<OrderStatus> orderStatuses = orderStatusMapper.queryOrderStatusList(dt);
/*
        //封装数据
        JSONObject result = new JSONObject();
        JSONObject datajson = new JSONObject();

        ArrayList<String> categories = new ArrayList<>();
        ArrayList<JSONObject> series = new ArrayList<>();

        JSONObject orderjson = new JSONObject();
        JSONObject refundjson = new JSONObject();

        ArrayList<Integer> orderconut = new ArrayList<>();
        ArrayList<Integer> refundconut = new ArrayList<>();


        for (OrderStatus orderStatus : orderStatuses) {
            categories.add(orderStatus.getTime());
            orderconut.add(orderStatus.getOrderCount());
            refundconut.add(orderStatus.getRefundCount());
        }

        orderjson.put("name", "新增订单量");
        orderjson.put("data", orderconut);

        refundjson.put("name", "退款订单量");
        refundjson.put("data", refundconut);

        series.add(orderjson);
        series.add(refundjson);

        datajson.put("categories", categories);
        datajson.put("series", series);

        result.put("status", 0);
        result.put("message", "获取数据成功");
        result.put("data", datajson);
*/

        ArrayList<Integer> orderconut = new ArrayList<>();
        ArrayList<Integer> refundconut = new ArrayList<>();
        ArrayList<String> categories = new ArrayList<>();

        for (OrderStatus orderStatus : orderStatuses) {
            categories.add(orderStatus.getTime());
            orderconut.add(orderStatus.getOrderCount());
            refundconut.add(orderStatus.getRefundCount());
        }
        SeriesData<Integer> orderconutseriesData = new SeriesData<>("新增订单量", orderconut);
        SeriesData<Integer> refundconutseriesData = new SeriesData<>("退款订单量", refundconut);
        ResponData responData = new ResponData("", 0, categories, Arrays.asList(orderconutseriesData, refundconutseriesData));
        return responData;
    }

    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Value("${di.redis.key}")
    String rdiskey;

    @Override
    public ResponData getRedisHotMobile() {
        Set<ZSetOperations.TypedTuple<String>> res = redisTemplate.opsForZSet().reverseRangeWithScores(rdiskey, 0, 5);


        /*//结果的json对象
        JSONObject result = new JSONObject();
        JSONObject datajson = new JSONObject();
        ArrayList<JSONObject> seriesjson = new ArrayList<>();
        JSONObject hotphoneJson = new JSONObject();
        ArrayList<Double> phonedata = new ArrayList<>();
        ArrayList<String> categoriesdata = new ArrayList<>();

        res.forEach(e -> {
            phonedata.add((e.getScore()));
            categoriesdata.add(e.getValue());
            System.out.println("手机型号：" + e.getValue() + "，访问量：" + e.getScore());
        });

        hotphoneJson.put("name", "手机型号");
        hotphoneJson.put("data", phonedata);

        seriesjson.add(hotphoneJson);

        datajson.put("series", seriesjson);
        datajson.put("categories", categoriesdata);

        result.put("status", 0);
        result.put("message", "获取数据成功");
        result.put("data", datajson);*/


        ArrayList<Double> phonedata = new ArrayList<>();
        ArrayList<String> categoriesdata = new ArrayList<>();

        res.forEach(e -> {
            phonedata.add((e.getScore()));
            categoriesdata.add(e.getValue());
        });
        SeriesData<Double> seriesData = new SeriesData<>("手机型号", phonedata);
        //javabean转换为JSON
        System.out.println(JSONObject.toJSON(seriesData));
        ResponData responData = new ResponData("", 0, categoriesdata, Arrays.asList(seriesData));

        return responData;
    }

    @Override
    public ResponData getCkSaleAmount() {
        List<SaleAmount> saleAmounts = orderStatusMapper.querySaleAmountList();

        ArrayList<Double> saledata = new ArrayList<>();
        ArrayList<String> categoriesdata = new ArrayList<>();

        saleAmounts.forEach(e -> {
            saledata.add(e.getAmount());
            categoriesdata.add(e.getBrand());
        });

        SeriesData<Double> seriesData = new SeriesData<>("销售金额", saledata);
        return new ResponData("", 0, categoriesdata, Arrays.asList(seriesData));

    }

    @Override
    public ResponData getCkSaleNum() {
        List<SaleAmountTotal> saleAmountTotals = orderStatusMapper.querySaleAmountTotalList();
        ArrayList<Double> todaysaledata = new ArrayList<>();
        ArrayList<Double> yestodaysaledata = new ArrayList<>();
        ArrayList<Double> passweeksaledata = new ArrayList<>();
        ArrayList<String> categoriesdata = new ArrayList<>();
        for (SaleAmountTotal saleAmountTotal : saleAmountTotals) {
            todaysaledata.add(saleAmountTotal.getTodaySaleAmount());
            yestodaysaledata.add(saleAmountTotal.getYestodaySaleAmount());
            passweeksaledata.add(saleAmountTotal.getPassweekSaleAmount());
            categoriesdata.add(saleAmountTotal.getBrand());
        }

        SeriesData<Double> todayseriesData = new SeriesData<>("今日销售额", todaysaledata);
        SeriesData<Double> yesdayseriesData = new SeriesData<>("昨日销售额", yestodaysaledata);
        SeriesData<Double> weekpassseriesData = new SeriesData<>("上周销售额", passweeksaledata);


        return new ResponData("", 0, categoriesdata, Arrays.asList(todayseriesData, yesdayseriesData, weekpassseriesData));
    }

    @Autowired
    ESDao esDao;

    @Override
    public JSONObject getEsSource() {

        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("agg_source").field("source").size(10);
        //1.返回查询结果
        SearchHits<Customer> searchHits = esDao.queryFromES(aggregationBuilder, Customer.class);

        Aggregations aggregations = searchHits.getAggregations();
        Terms terms = aggregations.get("agg_source");

        //2.获取buckets桶
        List<? extends Terms.Bucket> buckets = terms.getBuckets();

        JSONObject result = new JSONObject();
        ArrayList<JSONObject> dataarr = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            JSONObject dataPJ = new JSONObject();
            dataPJ.put("name", bucket.getKeyAsString());
            dataPJ.put("value", bucket.getDocCount());
            dataarr.add(dataPJ);
        }
        result.put("data", dataarr);
        result.put("status", 0);
        result.put("message", "");

        return result;
    }

    @Override
    public JSONObject getEsIndustry() {

        //1.准备聚合条件
        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("agg_profession").field("profession").size(10)
                .subAggregation(AggregationBuilders.terms("agg_sex").field("sex").size(2));
        SearchHits<Customer> searchHits = esDao.queryFromES(aggregationBuilder, Customer.class);

        //2.获取聚合结果
        Aggregations aggregations = searchHits.getAggregations();
        //3.获取分组数据
        Terms terms = aggregations.get("agg_profession");

        //4.获取桶
        List<? extends Terms.Bucket> buckets = terms.getBuckets();

        ArrayList<Long> manjson = new ArrayList<>();
        ArrayList<Long> wonmanjson = new ArrayList<>();
        ArrayList<String> categoriesdata = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            categoriesdata.add(bucket.getKeyAsString());

            Terms subTerms = bucket.getAggregations().get("agg_sex");
            List<? extends Terms.Bucket> subTermsBuckets = subTerms.getBuckets();
            for (Terms.Bucket subTermsBucket : subTermsBuckets) {
                if (subTermsBucket.getKeyAsString().equals("男")) {
                    long percent = subTermsBucket.getDocCount() * 100 / bucket.getDocCount();
                    manjson.add(percent);
                    wonmanjson.add(100 - percent);
                }
            }
        }

        SeriesData<Long> s1 = new SeriesData<>("男", manjson);
        SeriesData<Long> s2 = new SeriesData<>("女", wonmanjson);

        //1.将对象转换为字符串
        String jsonString = JSON.toJSONString(s1);
        //2.将字符串转换为json对象
        JSONObject jsonObject = JSON.parseObject(jsonString);
        jsonObject.put("unit", "%");

        JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(s2));
        jsonObject1.put("unit", "%");

        ArrayList<JSONObject> seriesjson = new ArrayList<>();

        seriesjson.add(jsonObject);
        seriesjson.add(jsonObject1);

        JSONObject data = new JSONObject();
        data.put("categories", categoriesdata);
        data.put("series", seriesjson);

        JSONObject result = new JSONObject();

        result.put("data", data);
        result.put("status", 0);
        result.put("message", "");
        return result;
    }

    @Override
    public JSONObject getCkProvinceSale(String province) {
        Double amount = orderStatusMapper.querySaleAmount(province);
        Double percent = 0d;
        if (amount > 10000000) {
            percent = 100d;
        } else {
            percent = amount * 100 / 10000000d;
        }
        JSONObject result = new JSONObject();
        result.put("status", 0);
        result.put("message", "");
        result.put("data", percent);
        return result;
    }

    @Override
    public JSONObject getCkProvinceSaleAndOrder() {
        List<ProvinceData> provinceData = orderStatusMapper.queryProvinceData();
        JSONObject result = new JSONObject();
        JSONObject datajson = new JSONObject();
        datajson.put("sizeValueName", "销售额");
        datajson.put("valueName", "下单数");
        datajson.put("mapData", provinceData);
        result.put("status", 0);
        result.put("message", "");
        result.put("data", datajson);

        return result;
    }

    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;
    @Value("${kafka.topic}")
    private String topic;

    @Override
    public void writeLogToKafka(String log) {
        System.out.println("发送消息到kafka" + log);
        kafkaTemplate.send(topic, log);
    }
}
